package club.gskj.system.controller;

import club.gskj.response.Result;
import club.gskj.system.service.AliOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/system")
@Api(value = "头像上传", tags = "系统头像上传")
@CrossOrigin
public class AliOssController {


    @Autowired
    private AliOssService aliOssService;

    /**
     * 头像上传
     */
    @ApiOperation(value = "上传头像", notes = "上传头像到oss")
    @PostMapping("/upload/avater")
    public Result uploadAvater(@RequestParam(value = "file") MultipartFile file) {
        String upload = aliOssService.upload(file);
        return Result.ok().data("url", upload);
    }

    /**
     * 删除 头像
     *
     * @param oldImage
     * @return
     */
    @ApiOperation(value = "删除头像", notes = "删除oss头像")
    @GetMapping("/deleteimg")
    public Result deletAvatar(@RequestParam("oldImage") String oldImage) {

        // https://moster0506.oss-cn-shanghai.aliyuncs.com/2020/11/25/f37bbf4b5cc449f6b08ff32269d8bbc1.png
        // 删除 图片只需要 2020/11/25/f37bbf4b5cc449f6b08ff32269d8bbc1.png
        String[] split = oldImage.split(".com/");
        System.out.println(split[1]);

        try {
            aliOssService.deleteFile(split[1]);
            return Result.ok();
        } catch (Exception e) {
            // TODO 打印日志到本地
            e.printStackTrace();
            return Result.error();
        }
    }
}
